<?php 

require_once 'config.php';

/** Authorizes the user.
 * Return TURE if successful otherwise FALSE. */
function user_login($email, $password) {
	$success = false;
	$mysqli = createMySQLi();
	$result = $mysqli->query("SELECT * FROM user WHERE email = '$email' AND password = '$password'");
	
	if($result != NULL && $result->num_rows > 0) {
		session_start();
		$_SESSION['user'] = $result->fetch_assoc();
		
		$result->close();
		$success = TRUE;
	}
	$mysqli->close();
	return $success;
}

/** Logs out the current user. */
function user_logout() {
	$_SESSION['user'] = NULL;
}

/** Obtain info from Facebook and saves to db. 
 * Return NULL if sucessfully otherwise the error string */
function user_register() {
	if ($_REQUEST) {
		// echo '<p>signed_request contents:</p>';
		$response = parse_signed_request($_REQUEST['signed_request'],
		FACEBOOK_SECRET);
		// echo '<pre>';
		// print_r($response);
		 
		if(checkUserExists($response['registration']['email'])) {
			return 'User already registered: ' . $response['registration']['email'];
		}
		
		$regError = createUserInDb($response['registration']['name'], $response['registration']['email'], $response['registration']['password'], $response['registration']['location']['name'], $response['registration']['gender'], $response['registration']['birthday'], $response['user']['country'], $response['user']['locale'], $response['user_id']);
		if($regError == NULL) {
			user_login($response['registration']['email'], $response['registration']['password']); // login here.
			
			return NULL;
		} else {
			return "SQL Error: $regError";
		}
		 
		// echo '</pre>';
	} else {
		return '$_REQUEST is empty';
	}
}

/** Returns NULL if successfully otherwise error string. */
function createUserInDb($name, $email, $password, $location, $gender, $birthday, $country, $locale, $facebook_id) {
	$mysqli = createMySQLi();
	$gender = $gender == 'male' ? 'M' : 'F';
	$sql = "INSERT INTO user (name, email, password, location, gender, birthday, country, locale, facebook_id) VALUES 
	('$name', '$email', '$password', '$location', '$gender', '$birthday', '$country', '$locale', '$facebook_id')";
	$stmt = $mysqli->prepare($sql);
	$stmt->execute();
	$affected_rows = $stmt->affected_rows;
	$errorStr = $affected_rows == 1 ? NULL : $mysqli->error;
	$mysqli->close();
	return $errorStr;
}

/** Returns TRUE if the user with the given email exists otherwise FALSE. */
function checkUserExists($email) {
	$mysqli = createMySQLi();
	$result = $mysqli->query("SELECT * FROM user WHERE email = '$email' LIMIT 1");
	$exists = $result != NULL && $result->num_rows > 0;
	$mysqli->close();
	return $exists;
}


// Copied from: http://developers.facebook.com/docs/plugins/registration/

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}



?>